import os
import tempfile
import webbrowser

import pyperclip

from kf.dict_enum_generate.window_dict_enum import delete_file
from util.comm.msg_util import msg
from util.database.cmd import run_cmd


def open_string_in_notepad(text):
    # 在Windows上，Notepad可以通过"notepad.exe"打开
    with tempfile.NamedTemporaryFile(delete=False, suffix=".txt") as temp_file:
        file_name = temp_file.name
        # 写入文本
        temp_file.write(text.encode('utf-8'))
        # 关闭文件
        temp_file.close()
        print(f'临时文件已创建，文件名为 {file_name}')
        run_cmd(f'notepad {file_name}')
    return file_name

def delete_temp_file(file_path):
    try:
        os.remove(file_path)
        print(f"File {file_path} has been deleted successfully.")
    except OSError as e:
        print(f"Error: {file_path} : {e.strerror}")

def watch_text_temp(text, encode='utf-8'):
    # 将文本保存到临时文件
    with open("temp.txt", "w", encoding=encode) as f:
        f.write(text)

    # 使用Notepad打开文件
    run_cmd(f'notepad temp.txt')

    with open("temp.txt", 'r', encoding=encode) as file:
        content = file.read()
        pyperclip.copy(content)

    delete_file("temp.txt")

def watch_html_temp(text, encode='utf-8'):
    # 将文本保存到临时文件
    with open("temp.html", "w", encoding=encode) as f:
        f.write(text)

    # 使用Notepad打开文件
    webbrowser.open('temp.html')

    # delete_file("temp.html")
